<template>
  <div class="payment">
    <div class="header">
      <a href="javascript:history.go(-1)"><img src="../assets/images/retreat.png" alt="" /></a>
      <span>支付</span>
    </div>
    <div class="pay-countdown">
      <div class="countdown">
        <span>支付剩余时间</span>
        <p>{{minute}}:{{second}}</p>
      </div>
      <div class="pay_price" v-if="isAllow && discountData.hasDiscountAmount">
        <span style="color:#f00;">-￥{{discountData.discountAmount}}</span>
        <p>满减优惠</p>
      </div>
      <div class="pay_price">
        <span>支付金额：{{amount}}</span>
        <p>{{this.$route.query.salesOutletName}}</p>
      </div>
    </div>
    <!-- <ul class="account">
      	<li>
      		<b></b>
      		<p>积分账户<span>本单可用&yen;0.02</span></p>
      		<span>0.00</span>
      	</li>
      	<li>
      		<b></b>
      		<p>现金账户<span>最多可使用&yen;175.01</span></p>
      		<span>0.00</span>
      	</li>
      </ul> -->
    <div v-if="paymentList.length>0" class="third-party-payment">
      <h4>第三方支付</h4>
      <ul class="payment-type" id="payType">
        <li v-for="(payment,key) in paymentList" @click="getPayMethod('method',$event)" :key="key">
          <b></b>
          <p v-bind="{paymenttype: payment.paymentType, paymentmethod: payment.paymentMethod,status:payment.status}">{{payment.name}}
            <span v-if="payment.status === false" style="color:#f00; font-size:0.35rem;">{{payment.description}}</span>
          </p>
        </li>
      </ul>
    </div>
    <button class="topayment" style="background: #a6dfdf;" v-if='displayNone || payStatus === false'>确认</button>
    <!-- <button class="topayment" v-else-if='payStatus === false' >确认</button> -->
    <button class="topayment" v-else @click="payPlat()">确认</button>
    <msg-box ref="msgBox"></msg-box>
    <!--提示信息-->
    <div :class="['pay-bg', {'display-none':isShowBlock === false}]"></div>
    <div :class="['pay-msg', {'display-none':isShowBlock === false}]">
      <div class="title">更多优惠折扣
        <span class="close" @click="closeBox"></span>
      </div>
      <!-- <div class="title">更多优惠折扣</div> -->
      <div class="info">
        壹键哥APP扫码支付仅需
        <span>{{this.yijiangeAmount}}</span>元，下载壹键哥APP享受更多优惠折扣！！
      </div>
      <p class="link" @click="payPlat()">
        <a href="javascript:void(0)">知道了</a>
      </p>
      <!-- <p class="link" @click="openGft"><a href="#">下载壹键哥APP去支付</a></p>
          <open-app ref="openApp"></open-app> -->
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import "vue-layer-mobile/need/layer.css";
import layer from "vue-layer-mobile";
import { setTimeout } from "timers";
import msgBox from './MsgBox';
import decimal from '../tools/decimal';
// import openApp from "./OpenApp";

Vue.use(layer);

export default {
  name: "payment",
  data() {
    return {
      showLoading: false,
      amount: 0,
      paymentList: [],
      status: false,
      minutes: "20",
      seconds: "12",
      merchantType: 1, //渠道
      payInfo: {},
      isAllow: false,
      discountData: {},
      yijiangeAmount: 0,
      isShowBlock: false,
      displayNone: false,
      payStatus: false,
      clientIP: "" // 搜狐IP
    };
  },
  components: {
    msgBox
  },
  mounted() {
    //this.getPaymentList();
    //检查是否可以使用满减活动优惠券
    this.checkAllowDiscount()
    this.countDown();
    this.clientIP = returnCitySN.cip || '';
    const ua = navigator.userAgent.toLowerCase();
    setTimeout(() => {
      const payType = document.getElementById("payType");
      const payList = payType.getElementsByTagName("p");
      for (let i = 0; i < payList.length; i++) {
        //微信打开，选中微信支付
        if (ua.indexOf("micromessenger") > 0) {
          if (payList[i].innerText.indexOf('微信') >= 0) {
            payList[i].click();
          }
        }

        //支付宝打开，选中支付宝
        if (ua.indexOf("alipay") > 0) {
          if (payList[i].innerText.indexOf('支付宝') >= 0) {
            payList[i].click();
          }
        }
      }
    }, 1000);
  },
  computed: {
    second: function() {
      return this.formaltTime(this.seconds);
    },
    minute: function() {
      return this.formaltTime(this.minutes);
    }
  },
  watch: {
    amount(val) {
      if (val < 0) this.amount = 0
    }
  },
  methods: {
    getPaymentList(amount) {
      this.$http.post("/api/getPaymentList", { payAmount: amount }).then(res => {
        if (res.body.isSuccess != 1) return false;
        const data = res.body.resData.payTypes;
        if (data.length > 0) {
          data.forEach((item, index) => {
            if (item.name.indexOf("微信支付") >= 0) {
              this.paymentList.push({
                name: item.name,
                status: item.status,
                description: item.description,
                paymentType: 6,
                paymentMethod: 6
              })
              // Vue.set(this.paymentList, index, {
              //   name: item.name,
              //   paymentType: 6,
              //   paymentMethod: 6
              // });
            } else if (item.name.indexOf("支付宝支付") >= 0) {
              this.paymentList.push({
                name: item.name,
                status: item.status,
                description: item.description,
                paymentType: 5,
                paymentMethod: 7
              })
            } else if (item.name.indexOf("云闪付") >= 0) {
              this.paymentList.push({
                name: item.name,
                status: item.status,
                description: item.description,
                paymentType: 17,
                paymentMethod: 17
              })
            }
          })
        }
      });
    },
    // openGft(){
    //         this.$refs.openApp.openApp()
    // },
    closeBox() {
      this.isShowBlock = !this.isShowBlock
      this.displayNone = false
    },
    showMsg() {
      //判断当前金额是否小于0
      if (this.amount <= 0) {
        this.alert('订单支付金额不得为0')
        return false
      } else if (this.isAllow) {
        this.isShowBlock = true
        this.yijiangeAmount = decimal.sub(this.amount, this.discountData.h5RealDiscount)
      }
      return false
    },
    alert(msg) {
      this.$refs.msgBox.alert(msg);
    },
    // 支付平台接口统一支付
    payPlat() {
      if (!this.isAllow && this.amount <= 0) {
        this.alert('订单支付金额不得为0')
        // if (this.isAllow) {
        //   this.isShowBlock = false
        // }
        return false
      }
      if (this.payInfo.paymentType == undefined || this.payInfo.paymentMethod == undefined) {
        this.$layer.toast({
          icon: "icon-check",
          content: "请选择支付方式！",
          time: 1500
        });
        // if (this.isAllow) {
        //   this.isShowBlock = false
        // }
        return false;
      }

      const host = window.location.href.split("#")[0];
      this.payInfo.returnUrl = `${host}#/result`;
      this.payInfo.merchantType = this.merchantType;
      this.payInfo.remark = "支付平台支付";
      this.payInfo.clientIP = this.clientIP;
      this.payInfo.wapUrl = host

      // if (this.isAllow) {
      //   this.isShowBlock = false
      // }
      // if(this.isAllow){
      //     this.isShowBlock = !this.isShowBlock
      //     this.yijiangeAmount = decimal.sub(this.amount,this.discountData.h5RealDiscount)
      // }else{
      //   this.toPayOrder()
      // }
      this.toPayOrder()
      this.displayNone = true
      return false
    },
    toPayOrder() {
      this.$http.post("/api/payPlat", this.payInfo).then(res => {
        if (res.data.isSuccess != 1) {
          this.$layer.toast({
            icon: "icon-check",
            content: res.data.description,
            time: 1500
          });
          return false;
        }

        if (this.payInfo.paymentType === 5) {
          let form = res.data.resData.aliHtml;
          let app = document.getElementById("app");
          let node = this.parseDom(form);
          app.appendChild(node[0]);
          document.forms["alipaysubmit"].submit();
          return false
        } else {
          // console.log(res)
          let link = res.data.resData.linkUrl;
          window.location.href = link;
          return false
        }

        return false;
        // 支付成功后操作？
        // this.$router.push({name: 'Result'})
      });
    },
    getPayMethod(str, event) {
      //移除所有的check样式
      const bTags = document.getElementsByTagName("b");
      for (let i = 0; i < bTags.length; i++) {
        bTags[i].removeAttribute("class");
      }

      const el = event.currentTarget;
      console.log('el:', typeof el.lastChild.getAttribute("status"))

      if (el.lastChild.getAttribute("status") && el.lastChild.getAttribute("status") === 'true') {
        this.payStatus = true
        el.firstChild.setAttribute("class", "check");
        this.payInfo.paymentType = parseInt(
          el.lastChild.getAttribute("paymenttype")
        );
        this.payInfo.paymentMethod = parseInt(
          el.lastChild.getAttribute("paymentmethod")
        );
      } else {
        this.payStatus = false
        this.$layer.toast({
          icon: "icon-check",
          content: "消费金额有限额，请在限额内支付",
          time: 1500
        });

        return false
      }

      //console.log(this.payInfo);
    },
    checkAllowDiscount() {
      this.amount = this.$route.query.amount;
      this.$http.post('/api/getDiscountAmnout').then((res) => {
        let result = res.body
        this.isAllow = result.isAllow
        this.discountData = result.data
        // this.isAllow  = true
        // this.discountData.hasDiscountAmount = true
        // this.discountData.discountAmount = 0.0011
        this.discountData.discountAmount = this.MathFloor(this.discountData.discountAmount)
        if (this.isAllow && this.discountData.hasDiscountAmount) {
          this.amount = decimal.sub(this.$route.query.amount, this.discountData.discountAmount)
        } else {
          this.amount = this.$route.query.amount;
        }
        this.getPaymentList(this.amount);
      })

      return false
    },
    MathFloor(val) {
      let numberFloat = decimal.mul(val, 100)
      return Math.floor(numberFloat) / 100
    },
    countDown() {
      let time = window.setInterval(() => {
        if (this.seconds == "00" && this.minutes != "00") {
          this.seconds = "59";
          this.minutes = parseInt(this.minutes);
          this.minutes--;
        } else if (this.minutes == "00" && this.seconds == "00") {
          //超时的逻辑
          window.clearInterval(time);
        } else {
          this.seconds = parseInt(this.seconds);
          this.seconds--;
          //this.seconds = this.formaltTime(this.seconds);
        }
      }, 1000);
    },
    formaltTime(time) {
      return time >= 10 ? "" + time : "0" + time;
    },
    formatPrice(value) {
      value = Number(value).toFixed(2);
      if (value === 0) {
        return 0.0;
      } else if (value.split(".")[1].substring(1) === 0) {
        value = Number(value).toFixed(1);
      }
      let _val = value.split(".");
      return _val[0] + "." + _val[1];
    },
    parseDom(e) {
      let div = document.createElement("div");
      if (typeof e === "string") {
        div.innerHTML = e;
      }
      return div.childNodes;
    }
  }
};
</script>

<style scoped>
/*主体样式*/

.payment {
  height: 100%;
  background: #f4f4f4;
  font-size: 0.4rem;
}

.pay-countdown {
  padding: 0 0.6667rem;
  background: #fff;
}

.countdown {
  padding: 0.4rem 0;
  border-bottom: 1px solid #f2f2f2;
  line-height: 0.9333rem;
  text-align: center;
}

.countdown span {
  color: #999999;
}

.countdown p {
  font-size: 0.56rem;
  color: #363636;
}

.pay_price {
  line-height: 1.44rem;
}

.pay_price span {
  float: right;
  color: #47cecf;
}

.account,
.payment-type {
  padding: 0 0.6667rem;
  background: #fff;
  margin-top: 0.4rem;
}

.account li,
.payment-type li {
  line-height: 1.52rem;
  border-bottom: 1px solid #fbfbfb;
  overflow: hidden;
}

.account li b,
.payment-type li b {
  float: left;
  width: 0.5867rem;
  height: 0.5867rem;
  background: url('../assets/images/nocheck.png') no-repeat;
  background-size: 100%;
  margin-top: 0.4267rem;
  margin-right: 0.2667rem;
}

.account li b.check,
.payment-type li b.check {
  background: url('../assets/images/check.png') no-repeat;
  background-size: 100%;
}

.account li:last-child,
.payment-type li {
  border: 0;
}

.account li p,
.payment-type li p {
  float: left;
}

.account li p>span {
  margin-left: 0.2rem;
  color: #afafaf;
  font-size: 0.32rem;
}

.account li>span {
  float: right;
  margin-right: 0.8rem;
  color: #47cecf;
}

.third-party-payment {
  margin-top: 0.2667rem;
}

.third-party-payment h4 {
  line-height: 0.88rem;
  padding-left: 0.6667rem;
  font-size: 0.4rem;
}

.payment-type {
  margin-top: 0;
}

.topayment {
  display: block;
  width: 7.72rem;
  height: 1.4rem;
  background: #09bebf;
  color: #fff;
  margin: 1.0667rem auto;
  font-size: 0.5333rem;
}

.display-none {
  display: none;
}


/*新加*/

.pay-bg {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  position: fixed;
  top: 0;
  left: 0;
}

.pay-msg {
  background: #fff;
  border-radius: 6px;
  position: fixed;
  top: 30%;
  z-index: 999;
  width: 94%;
  left: 3%;
  line-height: 1;
}

.pay-msg .title {
  font-size: 0.36rem;
  text-align: center;
  line-height: 3;
  position: relative;
  font-weight: 600;
}

.pay-msg .title .close {
  display: inline-block;
  width: 1rem;
  height: 1rem;
  background: url('../assets/images/vp-04.png') center no-repeat;
  background-size: 40% 40%;
  position: absolute;
  right: 0;
  top: 0;
}

.pay-msg .info {
  border-top: solid 1px #ddd;
  border-bottom: solid 1px #ddd;
  text-align: center;
  font-size: 0.34rem;
  padding: 0.2rem 10%;
  line-height: 2.6;
}

.pay-msg .info span {
  color: #ff392c;
  font-size: 0.34rem;
  font-weight: 600;
}

.pay-msg .link a {
  display: inline-block;
  text-align: center;
  color: #20c0d7;
  width: 100%;
  line-height: 3;
  font-size: 0.32rem;
}
</style>
